from rest_framework import serializers
from django_redis import get_redis_connection

# serializers.ModelSerializer
# serializers.Serializer

class RegisterSmscodeserializers(serializers.Serializer):
    text=serializers.CharField(label='用户输入验证码',max_length=4,min_length=4,required=True,allow_null=False)
    image_code_id=serializers.UUIDField(label='uuid')


    def validate(self, attrs):

        #获取用户的输入验证吗
        text = attrs.get('text')
        image_code_id=attrs['image_code_id']
        #链接redis  的code
        redis_conn=get_redis_connection('code')
        #获得redis的验证码

        redis_code=redis_conn.get('img_%s'%image_code_id)

        #判断code是否在
        if redis_code is None:
            raise serializers.ValidationError('验证码已过期')

        #获取了图片验证码之后，就把图片uuid删除
        redis_conn.delete('img_%s'%image_code_id)

        #3.比较

        if redis_code.decode().lower() !=text.lower():
            raise serializers.ValidationError('研制不一致')


        return attrs
